package com.qersoft.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qersoft.dao.QuestionBankDao;
import com.qersoft.entity.QuestionBank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service("QuestionBankService")
public class QuestionBankServiceImpl extends ServiceImpl<QuestionBankDao, QuestionBank> implements QuestionBankService {

    @Autowired
    private QuestionBankDao questionBankDao;

    @Override
    public boolean addQuestionBank(QuestionBank questionBank) {
        try {
            questionBank.setUpdateTime(LocalDateTime.now());
            int result = questionBankDao.insert(questionBank);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateQuestionBank(QuestionBank questionBank) {
        try {
            questionBank.setUpdateTime(LocalDateTime.now());
            int result = questionBankDao.updateById(questionBank);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteQuestionBank(QuestionBank questionBank) {
        try {
            // 删除数据库
            int result = questionBankDao.deleteById(questionBank.getId());
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<QuestionBank> getQuestionBankByExamId(String examId) {
        try {
            // 根据 examId 获取题库
            List<QuestionBank> questionBanks = questionBankDao.selectByExamId(examId);
            return questionBanks != null ? questionBanks : Collections.emptyList();
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    @Override
    public QuestionBank getQuestionBankById(Long id) {
        try {
            // 根据 ID 获取题库
            return questionBankDao.selectById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<QuestionBank> getQuestionsByCondition(QuestionBank condition) {
        QueryWrapper<QuestionBank> queryWrapper = new QueryWrapper<>();
        if (condition.getType()!= null) {
            queryWrapper.eq("type", condition.getType());
        }
        if (condition.getSubject()!= null) {
            queryWrapper.eq("subject", condition.getSubject());
        }
        // 可以根据其他可能的查询条件继续添加类似的判断和条件设置
        return questionBankDao.selectList(queryWrapper);
    }
}
